package com.wy.network.Transfer.basic;



import com.wy.network.util.StreamUtils;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;

/**
 * @author 吴宇~
 * @motto 我亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @date 2023/03/17/17:35
 */

/**
 * 可以传输文件名了
 */
public class Client_ {
    public static void main(String[] args) throws Exception {


        /**
         * 思路：
         * 客户端连接得到Socket对象
         * 我们把磁盘上的图片读取到文件数组里面去，
         * 创建读取文件磁盘的输入流
         * 使用了Buffered的话在shutdown前刷新一下，不然可能报错
         * 关流,设置结束的标志
         */
        //-----------------
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\transfer\\Transfer\\basic\\parameter.properties"));
        String sendFilePath = properties.getProperty("SendFilePath");
        String fileName_ = properties.getProperty("FileName");
        String port = properties.getProperty("port");
        String ip = properties.getProperty("ip");
        InetAddress inetAddress = InetAddress.getByName(ip);
        int Port = Integer.parseInt(port);
        //-------------------------
        String fileName = fileName_;
        String filePath = sendFilePath + fileName;
        //奇了怪了，传字符串就不可以，必须输才行
        Socket socket = new Socket(inetAddress, Port);
        OutputStream outputStream1 = socket.getOutputStream();
        //---------------
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream1);
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
        bufferedWriter.write(fileName);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        //---------------这部分写一个传输文件名的流

        OutputStream outputStream = socket.getOutputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
        byte[] bytes1 = StreamUtils.streamToByteArray(bufferedInputStream);//将文件信息读取到一个数组中
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);//buff就是增加了很多方法
//        outputStream.write(bytes1);       //这儿和上面这句一样
        bufferedOutputStream.write(bytes1);
        bufferedOutputStream.flush();//使用了Buffered的话在shutdown前刷新一下，不然可能报错
        socket.shutdownOutput();
        //到此为止，图片是发出去了，

        BufferedInputStream bufferedInputStream1 = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream1);
//        String s = StreamUtils.streamToString(bufferedInputStream1);
        System.out.println("客户端接收到了:" + new String(bytes));


        //-----所有的关流放在最后
        bufferedWriter.close();
        //-----
        bufferedInputStream1.close();
        bufferedOutputStream.close();
        bufferedInputStream.close();
        socket.close();

    }
}
